# 定义测试用例接口
from flask import request
from flask_restful import Resource

from api.verify_token import auth
from backend_server import db
from data_base.testcase_table import TestCase


class TestCaseAdd(Resource):
    method_decorators = [auth.login_required]

    def post(self):
        """
        新增用例
        """
        # 获取请求体中的数据保存到数据库
        try:
            data = TestCase(**request.json)
            print(data)
            db.session.add(data)
            db.session.commit()
        except Exception as e:
            return e
        return {'code': 0, "msg": "create success", 'data': data}

class TestCaseGet(Resource):
    method_decorators = [auth.login_required]

    def get(self):
        """
        新增用例
        """
        # 存在nodeid则按nodeid查询，默认查询所有的用例
        # 查找所有用例
        if request.args.get("nodeid"):
            test_cases = TestCase.query.filter_by(nodeid=TestCase.nodeid).first()
            if not test_cases:
                return {"msg": "case does not exist"}
            return {"msg": "get success", "data": test_cases.as_dict()}
        test_cases = TestCase.query.all()
        # 格式化case
        format_test_cases = [i.as_dict() for i in test_cases]
        print(format_test_cases)
        return {"msg": "get success", "data": format_test_cases}

class TestCaseDelete(Resource):
    method_decorators = [auth.login_required]

    def get(self):
        # 如果 url 中存在 option 参数为 del_testcase 代表要删除用例
        if "nodeid" in request.args:
            nodeid = request.args.get("nodeid")
            testcase = TestCase.query.filter_by(nodeid=nodeid).first()
            # 数据存在则执行删除，不存在抛出错误
            if not testcase:
                return {"msg": "case does not exist"}
            db.session.delete(testcase)
            db.session.commit()
            return {"msg": "delete success"}
        # 删除多个用例，比如 '[nodeid_1, nodeid_2, nodeid_3]'
        elif "nodeids" in request.args:
            # 利用 nodeid 参数指明要删除的用例
            nodeids = request.args.get("nodeids")
            for nodeid in nodeids.split(","):
                # 查询此用例后，进行删除
                testcase = TestCase.query.filter_by(nodeid=nodeid).first()
                db.session.delete(testcase)
            db.session.commit()
            return {"msg": "delete success"}
        else:
            return {"msg": "please input nodeid or nodeids!"}
class TestCaseUpdate(Resource):
    """
    更新测试用例
    """
    method_decorators = [auth.login_required]

    def post(self):
        request_body = request.json
        # print(request_body)
        # 用例nodeid存在则执行更新
        testcase = TestCase.query.filter_by(nodeid=request_body.get("nodeid")).first()
        if not testcase:
            return {"msg": "case does not exist"}
        # 更新数据的描述信息
        testcase.description = request_body.get("description")
        db.session.commit()
        return {"msg": "update success"}


























